package com.zyn.inventory.management.controller;

import java.util.Arrays;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.zyn.inventory.management.entities.User;
import com.zyn.inventory.management.enums.UserRole;
import com.zyn.inventory.management.forms.RegistrationForm;
import com.zyn.inventory.management.forms.UserForm;
import com.zyn.inventory.management.services.UserService;
import com.zyn.inventory.management.utils.Page;
import com.zyn.inventory.management.validator.UserFormValidator;


@Controller
public class UserController {
	private static final Logger log = LoggerFactory.getLogger(UserController.class);

    @Autowired(required = true)
    private UserService userService;
    
    private static final String HOME_PAGE = "redirect:/users";
    @Resource
    private UserFormValidator userFormValidator;
    
    @ModelAttribute("userRoles")
    public List<UserRole> userRoles(){
    	return Arrays.asList(UserRole.values());
    }
    

    @InitBinder("userForm")
    protected void initBinder(WebDataBinder binder) {
        binder.setValidator(userFormValidator);
    }
    
    @RequestMapping(value="/users",method=RequestMethod.GET)
    public String list(@RequestParam("page")Integer page,Model model){
    	Page<User> pageModel = this.userService.queryPage(page);
    	model.addAttribute("pageModel",pageModel);
    	return "ManagerUsers";
    }
    
    @RequestMapping(value="/user",method=RequestMethod.GET)
    public String showAddPage(Model model){
    	if(!model.containsAttribute("userForm")){
    		model.addAttribute("userForm",new UserForm());
    	}
    	return "UserAdd";
    }
    
    @RequestMapping(value="/users",method=RequestMethod.POST)
    public String saveUser(@Validated @ModelAttribute("userForm")UserForm userForm,BindingResult result,Model model){
    	log.info(userForm.toString());
    	if(result.hasErrors())
    		return showAddPage(model);
    	this.userService.registerUser(userForm.getUsername().trim(), userForm.getPassword().trim(), userForm.getRealName(),userForm.getUserRoles());
    	return HOME_PAGE;
    }
    
  
    //@RequestMapping(value = "/auth/register", method = RequestMethod.GET)
    public String showRegistrationPage(HttpServletRequest request, HttpServletResponse response, Model model, @RequestParam(required = false) String email) {

//        invalidateSession(request, response);

        if (!model.containsAttribute("registrationForm")) {
            RegistrationForm registrationForm = new RegistrationForm();
            model.addAttribute("registrationForm", registrationForm);
        }

        model.addAttribute("activeTab", "register");

        return "loginTH";
    }

    //@RequestMapping(value = "/auth/register", method = RequestMethod.POST)
    public String register(Model model, HttpServletRequest request, HttpServletResponse response, @ModelAttribute("registrationForm") @Validated RegistrationForm registrationForm, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return showRegistrationPage(request, response, model, null);
        }

//        invalidateSession(request, response);

        

        String[] codes = {"registration.failure"};

        ObjectError error = new ObjectError("registrationForm", codes, null, null);
        bindingResult.addError(error);

        return showRegistrationPage(request, response, model, null);
    }
}
